<template>
  <div style=" margin: 0px auto;padding-left: 15%;padding-right: 15%">
    <div style="display: flex;">
      <!-- 简介 -->
      <div style="width: 668px; height: 90px; display: flex; flex-direction: column; justify-content: space-between;">
        <div style="width: 668px; height: 28px;" class="video-title">
          <h1 style="">{{ video.videoTitle }}</h1>
        </div>
        <div style="display: flex; height: 24px; margin-top: 10px;">
          <div style="margin-right: 10px;">
            <i class="el-icon-video-play" style="padding-right: 5px;"></i>
            <span>254</span>
          </div>
          <div>
            <i class="el-icon-chat-dot-round" style="padding-right: 5px;"></i>
            <span style="margin-right: 5px;">123</span>
          </div>
          <div>
            <time style="margin-left: 10px;">{{ formatTimeAgo(video.createTime) }}</time>
          </div>
        </div>
      </div>

      <!-- 关注 -->
      <div style="width: 410px; height: 108px; margin-left: 20px">
        <div style=" display: flex;justify-content: flex-start;">
          <div style="width: 100px; text-align: center" class="up-cover">
            <el-image lazy :src="video.avatarUrl" @click="$router.push('/front/Space?id=' + video.authorId)"
              style="width: 50px; height: 50px; cursor: pointer; border-radius: 50%"></el-image>
          </div>
          <div class="right-div">
            <div class="up-nickname">
              <a> {{ video.userId }}</a>
            </div>
            <div class="up-introduction">
              <div style="width: 200px; height: 10px">
              </div>
              <span> {{ video.introduction }}</span>
            </div>

            <template>
              <div class="up-concern">
                <el-button v-if="!follow.isDelete == true" @click="followUser">+关注</el-button>
                <el-button v-if="follow.isDelete == true" style="background-color: #8c939d!important;"
                  @click="unfollowUser(frozenData.id)">已关注</el-button>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!--  video  -->
    <div style=" margin: 0px auto;">
      <div class='demo ' style="width: 668px;height: 376px;">
        <div class="custom-progress-bar">
          <!-- 在这里添加你自定义的进度条组件或样式 -->
        </div>
        <videoPlus2 ref="player" :url="videoUrl" :pic="videoPic" v-if="lock">
        </videoPlus2>
      </div>
      <div>
        <el-button v-if="!favorites.isDelete == true" @click="showForm = true" size="26px">
          <i class="el-icon-star-off" style="margin-right: 5px;font-size: 20px;"></i>
          收藏</el-button>
        <el-button v-if="favorites.isDelete == true" @click="unFavorites(favorites.id)" size="26px">
          <i class="el-icon-star-on" style="margin-right: 5px;font-size: 20px;"></i>
          已收藏</el-button>
      </div>

      <el-dialog title="添加到文件夹" :visible.sync="showForm" width="30%">
        <div>
          <el-radio v-for="tab in collection" :key="tab.id" v-model="selectedTab" :label="tab.id"
            :name="tab.collectionName">{{ tab.collectionName }}</el-radio>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showForm = false">取消</el-button>
          <el-button type="primary" @click="addFavorites">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <!--    评论  -->
    <div style="width: 668px;text-align: left ">

      <div style="margin-top: 20px;">
        <div style="border-bottom: 1px solid orangered; font-size: 20px">评论{{ totalComments }}</div>
        <div style="display: flex; align-items: center;margin-top: 20px;">
          <div style="width: 100px; text-align: center;">
            <el-image :src="user.avatarUrl"
              style="width: 50px; height: 50px; cursor: pointer; border-radius: 50%;"></el-image>
          </div>
          <div style="flex: 1;">
            <el-input placeholder="这里需要一条优质评论" v-model="commentForm.content"></el-input>
          </div>
          <div class="pd-10" style="text-align: right;">
            <el-button type="primary" style="width: 60px;height: 50px; margin-left: 10px"
              @click="saveComment()">发布</el-button>
          </div>
        </div>
      </div>

      <!--      评论列表-->
      <div style="width: 668px; text-align: left;margin-top: 10px">
        <div v-for="item in comments" :key="item.id" style="border-bottom: 1px solid #ccc; padding: 10px 0; ">
          <div style="display: flex">
            <!--  头像  item.avatarUrl-->
            <div style="width: 100px; text-align: center">
              <el-image :src="baseUrl + ':8081/file/download?type=videoCover&fileName=' + item.id"
                style="width: 50px; height: 50px;cursor: pointer; border-radius: 50%"></el-image>
            </div>
            <!--          中间  item.nickname-->
            <div style="flex: 1; font-size: 12px; font-family: SimHei, Arial, sans-serif;
                      font-weight: 500;padding: 5px 0; line-height: 25px;">
              <b style="cursor: pointer; font-family: SimHei, Arial, sans-serif;">{{ item.id }}</b>
              <!--            评论内容-->
              <span style="display: block; font-family: SimHei, Arial, sans-serif;
             font-size: 16px;line-height: 24px; ">{{ item.comment }}</span>
              <!--            评论时间-->
              <div style="display: flex; line-height: 20px; margin-top: 5px; align-items: center; color: #969aa1">
                <div style="width: fit-content;">
                  <i class="el-icon-time"></i><span style="margin-left: 5px;">{{ formatTimeAgo(item.createTime) }}</span>
                </div>
                <div style="flex: 1; line-height: 20px;margin-left: 10px" class="button-reply ">
                  <el-button class="comment-button" style="margin-left: 5px; color: #969aa1;" type="text"
                    @click="handleReply(item.id)">回复</el-button>
                  <el-button type="text" style="color: red;" @click="deleteComment(item.id)"
                    v-if="user.id === item.userId">删除</el-button>
                </div>
              </div>
            </div> <!--  内容-->
          </div>

          <!--        评论数量不超过三条显示的二级评论-->
          <div v-if="item.children.length > 3">
            <!--   二级评论-->
            <div v-if="item.children.length" style="padding-left: 90px;" class="comment-content1">
              <!-- 添加一个状态变量来切换显示/隐藏多余的评论 -->
              <div
                v-for="(subComment, subCommentIndex) in item.children.slice(0, item.showAllComments ? item.children.length : 3)"
                :key="subComment.id" v-show="!collapsedComments[item.id]"
                style="border-bottom: 1px solid #fff;;border-radius: 6px; ">
                <!-- 回复列表 -->
                <div style="font-size: 14px; padding: 5px 0; line-height: 25px;border-width: 10px; ">
                  <!-- 回复的@ -->
                  <!-- 图片，人名，回复内容 -->
                  <div style="padding-left: 5px;font-size: 16px;">
                    <el-image :src="subComment.avatarUrl"
                      style="width: 30px;cursor: pointer;  height: 30px;top: 8px; border-radius: 50%"></el-image>
                    <b style="margin-left: 8px;font-size: 14px;cursor: pointer; font-family: SimHei, Arial, sans-serif; ">{{
                      subComment.nickname }}</b>
                    <a v-if="subComment.pnickname !== item.nickname" class="comment-a"> <b style="color: #222222">回复</b>
                      @{{ subComment.pnickname }}:</a>
                    <a v-else></a>
                    <span style="color: #666666; font-family: SimHei, Arial, sans-serif;font-weight:400;font-size: 14px;">
                      {{ subComment.content }}</span>
                  </div>

                  <div style="display: flex; line-height: 20px; margin-top: 5px; align-items: center; color: #969aa1">
                    <div style="width:fit-content;">
                      <i class="el-icon-time"></i><span style="margin-left: 5px;">{{ formatTimeAgo(subComment.time)
                      }}</span>
                    </div>
                    <div style="flex: 1; line-height: 20px;margin-left: 10px">
                      <el-button style="margin-left: 5px;color: #969aa1" type="text"
                        @click="handleReply(subComment.id)">回复</el-button>
                      <el-button type="text" style="color: red" @click="del(subComment.id)"
                        v-if="user.id === subComment.userId">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 显示/隐藏二级评论的按钮 -->
              <div>
                <!-- 添加一个按钮或其他元素来切换显示/隐藏多余的评论 -->
                <el-button type="text" v-bind:item="item" v-on:click="toggleComments(item)" style="color: #8c939d">
                  <span v-if="!item.showAllComments">共{{ secondaryCommentsCount[item.id] }}条回复,</span>
                  {{ item.showAllComments ? '收起评论' : '点击查看' }}
                </el-button>
              </div>
            </div>
          </div>

          <!--        评论数量超过三条显示的二级评论-->
          <div v-else>
            <!--   二级评论-->
            <div v-if="item.children.length" style="padding-left: 90px;" class="comment-content1">
              <!-- 添加一个状态变量来切换显示/隐藏多余的评论 -->
              <div
                v-for="(subComment, subCommentIndex) in item.children.slice(0, item.showAllComments ? item.children.length : 3)"
                :key="subComment.id" v-show="!collapsedComments[item.id]"
                style="border-bottom: 1px solid #fff;;border-radius: 6px; ">
                <!-- 回复列表 -->
                <div style="font-size: 14px; padding: 5px 0; line-height: 25px;border-width: 10px; ">
                  <!-- 回复的@ -->
                  <!-- 图片，人名，回复内容 -->
                  <div style="padding-left: 5px;font-size: 16px;">
                    <el-image :src="subComment.avatarUrl"
                      style="width: 30px;cursor: pointer;  height: 30px;top: 8px; border-radius: 50%"></el-image>
                    <b style="margin-left: 8px;font-size: 14px;cursor: pointer;  font-family: SimHei, Arial, sans-serif;">{{
                      subComment.nickname }}</b>
                    <a v-if="subComment.pnickname !== item.nickname" class="comment-a"> <b style="color: #222222">回复</b>
                      @{{ subComment.pnickname }}:</a>
                    <a v-else></a>
                    <span style="color: #666666; font-family: SimHei, Arial, sans-serif;font-weight:400;font-size: 14px;">
                      {{ subComment.content }}</span>
                  </div>

                  <div style="display: flex; line-height: 20px; margin-top: 5px; align-items: center; color: #969aa1">
                    <div style="width:fit-content;">
                      <i class="el-icon-time"></i><span style="margin-left: 5px;">{{ formatTimeAgo(subComment.time)
                      }}</span>
                    </div>
                    <div style="flex: 1; line-height: 20px;margin-left: 10px;font-size: 16px">
                      <el-button class="comment-button" style="margin-left: 5px;color: #969aa1" type="text"
                        @click="handleReply(subComment.id)">回复</el-button>
                      <el-button type="text" style="color: red" @click="del(subComment.id)"
                        v-if="user.id === subComment.userId">删除</el-button>
                    </div>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>

      <el-dialog title="回复" :visible.sync="dialogFormVisible" width="50%">
        <el-form label-width="80px" size="small">
          <el-form-item label="回复内容">
            <el-input type="textarea" v-model="commentForm.contentReply" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="saveComment()" size="small">确 定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { getVideoDetail } from "@/api/video/video";

import videoPlus2 from "@/views/video/videoPlus2"
// import video5 from "@/views/video/video5"

export default {
  name: "VideoDetail",
  components: {
    videoPlus2
  },
  data() {
    return {
      id: this.$route.params.id,
      video: {},
      follow: {},
      favorites: {},
      collection: {},
      selectedTab: '',
      showForm: false, // 控制表单的显示和隐藏
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      comments: [],
      commentList: [], // 初始化评论详情为空数组
      commentForm: {},
      collapsedComments: {},
      dialogFormVisible: false,
      
      downloadUrl: process.env.VUE_APP_DOWNLOAD_URL,
      videoUrl: '',
      videoPic: '',
      lock: false,
    }
  },
  computed: {
    /*评论数*/
    totalComments() {
      let count = 0;
      this.comments.forEach(item => {
        count += 1; // 加上当前一级评论
        count += item.children.length; // 加上当前一级评论的二级评论数量
      });
      return count;
    },
    frozenData() {
      return this.follow;
    },
    /*每个一级评论下二级评论的数量*/
    secondaryCommentsCount() {
      const counts = {};
      this.comments.forEach((item) => {
        counts[item.id] = item.children.length;
      });
      return counts;
    }
  },

  created() {
    /*更新视频*/
    setTimeout(() => {
      this.loadVideo()
    }, 500);

    /*更新关注*/
    setTimeout(() => {
      this.loadFollow();
    }, 1000);

    /*更新评论*/
    this.loadComment()

    //更新收藏
    setTimeout(() => {
      this.loadFavorites()
    }, 1500);

    //更新收藏夹
    this.loadCollection()
  },

  methods: {
    loadVideo() {
      getVideoDetail(this.id).then(res => {
        this.video = res.data.data;
        this.videoUrl = this.downloadUrl + res.data.data.videoUrl;
        this.videoPic = this.downloadUrl + res.data.data.videoCover;
        console.log(this.videoUrl);
        document.title = res.data.data.videoTitle;
        this.lock = true;
      })
    },
    loadFollow() {
      this.request.get("/follow/getVideoFollow/" + this.user.id + "/" + this.video.authorId)
        .then(response => {
          this.follow = response.data;
        })
        .catch(error => {
          console.error(error);
        });
    },
    loadFavorites() {
      this.request.get("/favorites/getVideoFavorites/" + this.user.id + "/" + this.video.id)
        .then(response => {
          if (response.data) {
            this.favorites = response.data;
          } else {
            console.log('着急报错是吧');
          }
        })
        .catch(error => {
          console.error(error);
        });
    },
    loadComment() {
      this.request.get("/comment/getVideoComment/" + this.id).then(res => {
        this.comments = res.data;
        this.selectedTab = res.data.collectionName
        this.$forceUpdate(); // 强制更新组件
      });
    },
    loadCollection() {
      this.request.get("/collections/getUserCollection/" + this.user.id).then(res => {
        this.collection = res.data
        console.log(this.collection)
      })
    },

    // getCommentVideoDetail() {
    //   this.request.get(`/comment/findCommentVideoDetail/` + this.originId)
    //       .then(response => {
    //         this.commentList = response.data; // 将返回的评论详情列表赋值给commentList
    //       })
    //       .catch(error => {
    //         console.error('请求出错:', error);
    //       });
    // },
    toggleComments(item) {
      this.$set(item, 'showAllComments', !item.showAllComments);
    },

    /*添加收藏*/
    addFavorites() {
      if (!this.user.id) {
        this.$message.warning("请登录后操作");
        return;
      }
      const data = {
        videoId: this.video.id,
        title: this.video.videotitle,
        videoCover: this.video.videoCover,
        collectionsId: this.selectedTab
      };
      console.log('777' + data.collectionsId)
      this.request.post("/favorites/save", data).then(res => {
        if (res.code === '200') {
          this.loadFavorites()
          this.showForm = false
          this.$message.success("收藏成功");
        }
        else {
          this.$message.error(res.msg + "收藏失败");
        }
      })
    },
    unFavorites(id) {
      // 执行取消收藏的逻辑
      this.request.get("/favorites/del" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("取消收藏")
          this.loadFavorites()
        } else {
          this.$message.error("取消收藏失败")
        }
      })
      // ...
      this.loadFavorites()
    },

    /*关注*/
    followUser() {
      if (!this.user.id) {
        this.$message.warning("请登录后操作");
        return;
      }
      // 执行关注用户的逻辑
      const data = {
        followedUserId: this.video.authorId
      };
      this.request.post("/follow/save", data).then(res => {
        if (res.code === '200') {
          this.$message.success("关注成功");
          this.loadFollow()
        }
        else {
          this.$message.error(res.msg + "关注失败");
        }
      })
      this.loadFollow()
    },
    unfollowUser(id) {
      // 执行取消关注的逻辑
      this.request.get("/follow/del" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("取消关注")
          this.loadFollow()
        } else {
          this.$message.error("取消关注失败")
        }
      })
      this.loadFollow()
    },

    // 发起评论
    saveComment() {
      if (!this.user.id) {
        this.$message.warning("请登录后操作");
        return;
      }
      this.commentForm.videoId = this.id;
      if (this.commentForm.contentReply) {
        this.commentForm.content = this.commentForm.contentReply;
      }
      // 去除前后空格
      this.commentForm.content = this.commentForm.content.trim();

      if (this.commentForm.content == null || this.commentForm.content === "") {
        this.$message.error("请输入评论");
        return false;
      }

      this.request.post("/comment/save", this.commentForm).then(res => {
        if (res.code === '200') {
          this.$message.success("评论成功");
          this.commentForm = {};  // 初始化评论对象内容
          this.loadComment();
          this.dialogFormVisible = false;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    deleteComment(id) {
      this.request.get("/comment/del" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("删除成功")
          this.loadComment()
        } else {
          this.$message.error("删除失败")
        }
      })
    },

    // 进行回复
    handleReply(pid) {
      this.commentForm = { pid: pid }
      this.dialogFormVisible = true
    },

    /*上传时间*/
    formatTimeAgo(uploadDate) {
      const date = new Date(uploadDate);
      const now = new Date();
      const diffInMilliseconds = now - date;
      const diffInMinutes = Math.floor(diffInMilliseconds / (1000 * 60));

      if (diffInMinutes < 1) {
        return '刚刚';
      } else if (diffInMinutes < 60) {
        return diffInMinutes + '分钟前';
      } else {
        const diffInHours = Math.floor(diffInMilliseconds / (1000 * 60 * 60));

        if (diffInHours === 1) {
          return '1小时前';
        } else if (diffInHours < 24) {
          return diffInHours + '小时前';
        } else if (diffInHours < 48) {
          const hour = date.getHours();
          const minute = date.getMinutes();
          return '昨天 ' + hour + ':' + minute;
        } else if (diffInHours < 72) {
          return "2天前";
        } else {
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          const hour = date.getHours();
          const minute = date.getMinutes();
          return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
        }
      }
    },
  },
}
</script>

<style >
/*视频标题*/
.video-title h1 {
  font-size: 20px;
  font-family: PingFang SC, HarmonyOS_Regular, Helvetica Neue, Microsoft YaHei, sans-serif;
  font-weight: 500;
  -webkit-font-smoothing: antialiased;
  color: #18191C;
  line-height: 28px;
  margin-bottom: 6px;
  text-overflow: ellipsis;
}

/*回复按钮*/
.comment-button :hover {
  color: #42b983;
}

/**/
.comment-a:hover {
  color: #F56C6C !important;
}

.hover-container:hover .comment-a {
  color: red;
}

.comment-content1 a {
  color: #4078c6 !important;
  cursor: pointer;
  font-family: SimHei, Arial, sans-serif;
  text-align: center;
  margin-left: 9px;
  font-size: 14px
}

.pd-10 span {
  font-size: 16px;
  text-align: center;

}

.pd-10 :hover {}

.el-input el-input--mini {
  height: 50px !important;
  line-height: 28px !important;
}

.up-cover {
  display: flex;
  justify-content: center;
  align-items: center;
}

.right-div {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  font-family: SimHei, Arial, sans-serif;
}

.up-nickname a {
  color: #BE7E4A;
  cursor: pointer;
}

.up-introduction {
  margin-top: 5px;
}

.up-introduction span {
  color: #8c939d;
  line-height: 18px;
  display: -webkit-box;
  overflow: hidden;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  line-break: anywhere;
  -webkit-line-clamp: 1;
  font-size: 14px;
}

.up-concern .el-button {
  background-color: #57C3C2 !important;
  color: white !important;
  margin-top: 5px;
  width: 200px;
  border-radius: 7%;
}

/*进度条*/
/* .video-player-box .vjs-progress-holder .vjs-play-progress {
  background-color: #409EFF;
} */

.vjs-control-bar {
  height: 50px !important;
  width: 100%;
  background-color: #ccc;
}

/*进度条*/
.video-js .vjs-progress-control {
  height: 3px;
  width: 100% !important;
}

/*暂停键*/
.custom-progress-bar {
  /* 根据需要调整样式和位置 */
  background-color: #ccc;
}

.vjs-button>.vjs-icon-placeholder::before {
  font-size: 2.8em;
}
</style>
